// 创建暴力用的序列
// 全排列
class CreateSeries {
    constructor(len) {
        this.len = len;
        this.all = [];
        this.tmp = [];
        this.book = [];
        this.cur = 0;
        for (var i = 0;i < len;i++) {
            this.book[i] = 0;
        }
    }
    dfs(step = 0) {
        if (step === this.len) {
            this.all.push(JSON.parse(JSON.stringify(this.tmp)));
            return ;
        }
        for (var i = 0;i < this.len;i++) {
            if (this.book[i] === 0) {
                this.tmp[step] = i;
                this.book[i] = 1;
                this.dfs(step + 1);
                this.book[i] = 0;
            }
        }
    }
    getNext() {
        if (this.cur < this.all.length) {
            return this.all[this.cur++];
        } else {
            this.cur = 0;
            return false;
        }
    }
}

// 合并全排列
class CreateSeriesMerge {
    // list = [[a,b],[c,d],[e]]
    constructor(list) {
        this.list = list;
        this.css = list.map(l => new CreateSeries(l.length));
        this.all = [];
    }

    /**
     * [ab cd e]
     * [ab dc e]
     * [ba cd e]
     * [ba dc e]
     */
    getAll() {
        let $this = this;
        this.css.forEach(c => c.dfs());
        let o = [];
        let tmp = [];
        let r = function (i) {
            if (i < $this.css.length) {
                while (true) {
                    let l = $this.css[i].getNext();
                    if (l) {
                        o.push(l);
                        r(i + 1);
                        o.pop(l);
                    } else {
                        break;
                    }
                }
            } else {
                tmp = [];
                o.forEach((oo,oind) => {
                    oo.forEach(ind => {
                        tmp.push($this.list[oind][ind]);
                    });
                });
                $this.all.push(JSON.parse(JSON.stringify(tmp)));
            }
        };
        r(0);
    }
}

module.exports = {
    CreateSeries,
    CreateSeriesMerge,
}
